package serviceImpl;

import dao.*;
import serviceInterface.queryInterface;

/**
 * @author Delta
 * Created in 2021-06-09 21:51
 */
public class queryMod implements queryInterface{
    //内部调用DAO方法
    private boolean query(char scope, char type, String ...strings) {
        boolean res;
        String flag = (""+scope+type).toUpperCase();
        switch (flag){
            case "GI":
                res = new GroupDAO().query('I', checkId(strings[0]));
                break;
            case "GN":
                res = new GroupDAO().query('N', checkName(strings[0]));
                break;
            case "UI":
                res = new UserDAO().query('I',checkId(strings[0]));
                break;
            case "UN":
                res = new UserDAO().query('N', checkName(strings[0]));
                break;
            case "UA":
                res = new UserDAO().query('A',checkName(strings[0]), checkName(strings[1]));
                break;
            default:
                throw new RuntimeException("Parameter Mismatch!");
        }
        return res;
    }
    //匹配五位数字，不匹配抛出异常
    private String checkId(String str){
        if(!str.matches("\\d{5}")) {
            throw new RuntimeException("\nFormatException: " +
                    "For input Id: \""+str+"\"\n" +
                    "Current Format is like \"10001\"\n");
        } else {
            return str;
        }
    }
    //匹配字母、数字、下划线、汉字，不匹配抛出异常
    private String checkName(String str){
        if(!str.matches("[\\u4E00-\\u9FA5,\\w]{1,16}")/* || str.matches("^_.*$")*/){
            throw new RuntimeException("\nFormatException: " +
                    "For input : \""+str+"\"\n" +
                    "Current Format is like \"ABC_你好123_再见\"\n");
        } else {
            return str;
        }
    }

    //供外部使用的方法
    public boolean queryUserById(int uid){return query('U','I', ""+uid);}
    public boolean queryUserByName(String uname){return query('U','N', uname);}
    public boolean queryUserByAccount(String account, String password){return query('U','A', account, password);}
    public boolean queryGroupById(int gid){return query('G','I', ""+gid);}
    public boolean queryGroupByName(String gname){return query('G','N', gname);}

}
